package com.hzhr.iot.web.controller;

import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDeviceGetModel;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDeviceModel;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDevicePostModel;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDevicePutModel;
import com.hzhr.iot.device.sdk.model.nbMeter.NbMeterDeleteModel;
import com.hzhr.iot.device.sdk.model.nbMeter.NbMeterPostModel;
import com.hzhr.iot.device.sdk.model.nbMeter.NbMeterPutModel;
import com.hzhr.iot.device.sdk.model.nbMeter_sell.NbMeter_SellPostModel;
import com.hzhr.iot.device.sdk.service.Device_IotDeviceService;
import com.hzhr.iot.device.sdk.service.Device_NbMeterService;
import com.hzhr.iot.device.sdk.service.Device_NbMeter_SellService;
import com.hzhr.iot.login.sdk.model.userCard.UserCardModel;
import com.hzhr.iot.web.constant.DeviceOptions;
import com.hzhr.iot.web.controller.base.BaseController;
import com.hzhr.iot.web.model.response.BaseResponse;
import com.hzhr.iot.web.util.DateHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;


@RequestMapping("/iotdevice")
@Api(description = "物联网设备")
@RestController
public class IotDeviceController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    Device_IotDeviceService device_iotDeviceService;
    @Autowired
    DeviceOptions deviceOptions;
    @Autowired
    Device_NbMeterService device_nbMeterService;
    @Autowired
    Device_NbMeter_SellService device_nbMeter_sellService;

    @ApiOperation(value = "获取物联网设备", notes = "获取物联网设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码",required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "单页面条数", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "设备ID", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "begintime", value = "开始时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "endtime", value = "结束时间，形如2018-01-01 23:00:00", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "安装地址", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "isvalid", value = "状态,1启用 0停用 -1全部", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "issale", value = "是否出售,1出售 0待售 -1全部", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "deviceid", value = "设备号", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gascompanyId", value = "所属然气公司ID", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "iotcompanyId", value = "所属物联公司ID", required =false,dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/getiotdevicelist", method = RequestMethod.POST)
    BaseResponse getiotdevicelist(@RequestParam(value ="pageNum", required = false) Integer pageNum,
                                  @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                  @RequestParam(value = "uat", required = true) String uat,
                                  @RequestParam(value = "id", required = false) String id,
                                  @RequestParam(value = "begintime", required = false) String begintime,
                                  @RequestParam(value = "endtime", required = false) String endtime,
                                  @RequestParam(value = "address", required = false) String address,
                                  @RequestParam(value = "isvalid", required = false) Integer isvalid,
                                  @RequestParam(value = "issale", required = false) Integer issale,
                                  @RequestParam(value = "deviceid", required = false) String deviceid,
                                  @RequestParam(value = "gascompanyId", required = false) String gascompanyId,
                                  @RequestParam(value = "iotcompanyId", required = false) String iotcompanyId) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show", "list");
        query.put("page", pageNum);
        query.put("count", pageSize);
        query.put("show_info", true);
        query.put("show_gasCompany", true);
        query.put("show_total", true);

        if (!StringUtils.isEmpty(deviceid)) {
            query.put("like_code", deviceid + "%");
        }
        if (issale != null) {
            if (issale == 0) {
                query.put("isnull_gasCompanyId", true);
            } else if (issale == 1) {
                query.put("isnull_gasCompanyId", false);
            }
        }
        if (!StringUtils.isEmpty(begintime)) {
            query.put("greaterthanorequal_createTime", HzhrDateUtil.strToDate(begintime).getTime());
        }
        if (!StringUtils.isEmpty(endtime)) {
            query.put("lessthan_createTime", HzhrDateUtil.strToDate(endtime).getTime());
        }
        query.put("equal_categoryCode", deviceOptions.getCode("IOT_DEVICE_CATEGORY", "NB_IOT_GAS_METER"));//默认是物联网表

        if (pageNum != null) {
            query.put("page", pageNum);
        }
        if (pageSize != null) {
            query.put("count", pageSize);
        }

        IotDeviceGetModel iotDeviceGetModel = device_iotDeviceService.get(header, query);
        List<IotDeviceModel> iotDeviceModels = iotDeviceGetModel.getModelList();
        int total = iotDeviceGetModel.getTotal();

        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (IotDeviceModel iotDeviceModel :
                iotDeviceModels) {
            Map<String, Object> dataItem = new HashMap<>();
            dataItem.put("id", HzhrTypeUtil.object2string(iotDeviceModel.getId()));
            dataItem.put("deviceid", HzhrTypeUtil.object2string(iotDeviceModel.getCode()));
            dataItem.put("des", HzhrTypeUtil.object2string(iotDeviceModel.getDes()));
            dataItem.put("createtime", HzhrTypeUtil.object2string(iotDeviceModel.getCreateTime()));
            dataItem.put("updatetime", HzhrTypeUtil.object2string(iotDeviceModel.getUpdateTime()));
            dataItem.put("saletime", HzhrTypeUtil.object2string(iotDeviceModel.getSaleTime()));
            dataItem.put("remarks", HzhrTypeUtil.object2string(iotDeviceModel.getRemark()));
            dataItem.put("bindstatus", HzhrTypeUtil.object2string(iotDeviceModel.getBindStatus()));
            dataItem.put("nbidentity", HzhrTypeUtil.object2string(iotDeviceModel.getIotPlatformImei()));
            dataItem.put("sim", HzhrTypeUtil.object2string(iotDeviceModel.getSimNo()));
            dataItem.put("type", "104");//默认是物联网表

            String reportTime = iotDeviceModel.getReportTime();
            if (reportTime != null) {
                dataItem.put("reporttime", reportTime);
            }

            Map<String, Object> userCompany_gascompanyId = new HashMap<>();
            userCompany_gascompanyId.put("name", HzhrTypeUtil.object2string(iotDeviceModel.getGasCompanyShortName()));
            dataItem.put("userCompany_gascompanyId", userCompany_gascompanyId);

            Map<String, Object> options_simtype = new HashMap<>();
            options_simtype.put("name", HzhrTypeUtil.object2string(iotDeviceModel.getSimTypeDes()));
            dataItem.put("options_simtype", options_simtype);

            Map<String, Object> options_reportperiod = new HashMap<>();
            options_reportperiod.put("name", HzhrTypeUtil.object2string(iotDeviceModel.getReportPeriodDes()));
            dataItem.put("options_reportperiod", options_reportperiod);

            dataItem.put("isvalid", "1");
            dataList.add(dataItem);
        }
        result.put("dataList", dataList);
        result.put("total", total);

        return new BaseResponse("0", "成功", result);
    }


    @ApiOperation(value = "新增物联网设备", notes = "新增物联网设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "deviceid", value = "设备号,最多20个字符", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "model", value = "设备型号,最多输入15个字符", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "des", value = "设备描述,最多输入80个字符", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "安装地址,最多输入50个字符", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "installtime", value = "安装时间,(yyyy-MM-dd HH:mm:ss)", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "longitude", value = "经度", required =false,dataType = "double", paramType = "query"),
            @ApiImplicitParam(name = "latitude", value = "纬度", required =false,dataType = "double", paramType = "query"),
            @ApiImplicitParam(name = "sim", value = "SIM卡,最多输入15个字符", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "simtype", value = "SIM卡类型", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "protocol", value = "设备协议", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "remarks", value = "备注,最多输入80个字符", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "nbserialnum", value = "NB设备ID,设备类型为NB时必填", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "nbidentity", value = "NB设备标识码，设备类型为NB时必填", required =true,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reporttime", value = "上报时间", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "weaksec", value = "自醒时长", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "peakdelaysec", value = "错峰延迟时间", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "reportperiod", value = "上报周期", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "bindstatus", value = "绑定状态, T_B_OPTION.TYPECODE='C_BDZT'", required =false,dataType = "int", paramType = "query"),
    })
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    BaseResponse add(@RequestParam(value = "uat", required = true) String uat,
                                  @RequestParam(value = "deviceid", required = false) String deviceid,
                                  @RequestParam(value = "type", required = false) Integer type,
                                  @RequestParam(value = "model", required = false) String model,
                                  @RequestParam(value = "des", required = false) String des,
                                  @RequestParam(value = "address", required = false) String address,
                                  @RequestParam(value = "installtime", required = false) String installtime,
                                  @RequestParam(value = "longitude", required = false) Double longitude,
                                  @RequestParam(value = "latitude", required = false) Double latitude,
                                  @RequestParam(value = "sim", required = false) String sim,
                                  @RequestParam(value = "simtype", required = false) Integer simtype,
                                  @RequestParam(value = "protocol", required = false) Integer protocol,
                                  @RequestParam(value = "remarks", required = false) String remarks,
                                  @RequestParam(value = "nbserialnum", required = false) String nbserialnum,
                                  @RequestParam(value = "nbidentity", required = true) String nbidentity,
                                  @RequestParam(value = "reporttime", required = false) String reporttime,
                                  @RequestParam(value = "weaksec", required = false) Integer weaksec,
                                  @RequestParam(value = "peakdelaysec", required = false,defaultValue = "") Integer peakdelaysec,
                                  @RequestParam(value = "reportperiod", required = false,defaultValue = "") String reportperiod,
                                  @RequestParam(value = "bindstatus", required = false,defaultValue = "") Integer bindstatus,
                                  @RequestParam(value = "code", required = false,defaultValue = "") String code) throws Exception {

        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        NbMeterPostModel body = new NbMeterPostModel();
        body.setImei(nbidentity);
        body.setDes(des);
        body.setRemark(remarks);
        device_nbMeterService.post(header, query, body);
        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "编辑物联网设备", notes = "编辑物联网设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "deviceid", value = "设备号,最多20个字符", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "model", value = "设备型号,最多输入15个字符", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "des", value = "设备描述,最多输入80个字符", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "address", value = "安装地址,最多输入50个字符", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "installtime", value = "安装时间,(yyyy-MM-dd HH:mm:ss)", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "longitude", value = "经度", required =false,dataType = "double", paramType = "query"),
            @ApiImplicitParam(name = "latitude", value = "纬度", required =false,dataType = "double", paramType = "query"),
            @ApiImplicitParam(name = "sim", value = "SIM卡,最多输入15个字符", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "simtype", value = "SIM卡类型", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "protocol", value = "设备协议", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "deptid", value = "管理部门", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "remarks", value = "备注,最多输入80个字符", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", required =true,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "nbserialnum", value = "NB设备ID,设备类型为NB时必填", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "nbidentity", value = "IMEI号，设备类型为NB时必填", required =true,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reporttime", value = "上报时间", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "weaksec", value = "自醒时长", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "peakdelaysec", value = "错峰延迟时间", required =false,dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "bindstatus", value = "绑定状态, T_B_OPTION.TYPECODE='C_BDZT'", required =false,dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "saletime", value = "出售时间,(yyyy-MM-dd HH:mm:ss)", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "reportperiod", value = "上报周期", required =false,dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isvalid", value = "是否有效  0.停用  1启用", required =false,dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "issale", value = "就否出售  0.未出售 1.出售 ", required =false,dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "source", value = "来源 1.接口  2.网站", required =false,dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    BaseResponse edit(@RequestParam(value = "uat", required = true) String uat,
                     @RequestParam(value = "deviceid", required = false) String deviceid,
                     @RequestParam(value = "type", required = false) Integer type,
                     @RequestParam(value = "model", required = false) String model,
                     @RequestParam(value = "des", required = false) String des,
                     @RequestParam(value = "address", required = false) String address,
                     @RequestParam(value = "installtime", required = false) String installtime,
                     @RequestParam(value = "longitude", required = false) Double longitude,
                     @RequestParam(value = "latitude", required = false) Double latitude,
                     @RequestParam(value = "sim", required = false) String sim,
                     @RequestParam(value = "simtype", required = false) Integer simtype,
                     @RequestParam(value = "protocol", required = false) Integer protocol,
                     @RequestParam(value = "deptid", required = false) String deptid,
                     @RequestParam(value = "remarks", required = false) String remarks,
                     @RequestParam(value = "id", required = true) String id,
                      @RequestParam(value = "nbserialnum", required = false) String nbserialnum,
                      @RequestParam(value = "nbidentity", required = true) String nbidentity,
                      @RequestParam(value = "reporttime", required = false) String reporttime,
                      @RequestParam(value = "weaksec", required = false) Integer weaksec,
                      @RequestParam(value = "peakdelaysec", required = false) Integer peakdelaysec,
                      @RequestParam(value = "reportperiod", required = false) String reportperiod,
                      @RequestParam(value = "saletime", required = false) String saletime,
                      @RequestParam(value = "bindstatus", required = false) Integer bindstatus,
                      @RequestParam(value = "code", required = false) String code,
                      @RequestParam(value = "isvalid", required = false) Integer isvalid,
                      @RequestParam(value = "issale", required = false) Integer issale,
                      @RequestParam(value = "source", required = false) Integer source) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        NbMeterPutModel body = new NbMeterPutModel();
        body.setDes(des);
        body.setRemark(remarks);
        device_nbMeterService.put(header, Integer.parseInt(id), query, body);
        return new BaseResponse("0", "成功");
    }


    @ApiOperation(value = "出售", notes = "出售")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "gascompanyid", value = "然气公司ID", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping(value = "/sell", method = RequestMethod.POST)
    BaseResponse sell(
                      @RequestParam(value = "uat", required = true) String uat,
                      @RequestParam(value = "id", required = true) String id,
                      @RequestParam(value = "gascompanyid", required = true) String gascompanyid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        NbMeter_SellPostModel body = new NbMeter_SellPostModel();
        body.setPurchasingCompanyId(Integer.parseInt(gascompanyid));
        device_nbMeter_sellService.post(header, Integer.parseInt(id), query, body);
        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "拆除", notes = "拆除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "id", value = "id", dataType = "String", required = true, paramType = "query")
    })
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    BaseResponse del(@RequestParam(value = "uat", required = true) String uat,
                          @RequestParam(value = "id", required = true,defaultValue = "0") String id) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        device_nbMeterService.delete(header, Integer.parseInt(id), query);
        return new BaseResponse("0", "成功");
    }

    @ApiOperation(value = "列表页顶部统计数据", notes = "列表页顶部统计数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uat", value = "用户登录令牌", dataType = "String", required = true, paramType = "query"),
            @ApiImplicitParam(name = "iotcompanyid", value = "物联网公司ID", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "gascompanyid", value = "然气公司ID", dataType = "int", required = false, paramType = "query")
    })
    @RequestMapping(value = "/listtopcount", method = RequestMethod.POST)
    BaseResponse listtopcount(@RequestParam(value = "uat", required = true) String uat,
                     @RequestParam(value = "iotcompanyid", required = false,defaultValue = "0") int iotcompanyid,
                              @RequestParam(value = "gascompanyid", required = false,defaultValue = "0") int gascompanyid) throws Exception {
        String token = getToken();
        Map<String, String> header = new HashMap<>();
        header.put("token", token);
        Map<String, Object> query = new HashMap<>();
        query.put("show_total", true);

        //默认为NB物联网表
        query.put("equal_categoryCode", deviceOptions.getCode("IOT_DEVICE_CATEGORY", "NB_IOT_GAS_METER"));

        query.put("greaterthanorequal_createTime", DateHelper.getTimesWeekmorning().getTime());
        int weekAddCount = device_iotDeviceService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", DateHelper.getDayEndTime(new Date()).getTime());
        int yesterdayAddCount = device_iotDeviceService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", DateHelper.getMonthBeginTime(new Date()).getTime());
        int monthAddCount = device_iotDeviceService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", DateHelper.getCurrYearFirst().getTime());
        int yearAddCount = device_iotDeviceService.get(header, query).getTotal();
        query.put("greaterthanorequal_createTime", null);
        int deviceCount = device_iotDeviceService.get(header, query).getTotal();


        HashMap<String,Object> map=new HashMap<>();
        map.put("WeekAddCount",weekAddCount);//周新增设备
        map.put("YesterdayAddCount",yesterdayAddCount);//昨日新增设备
        map.put("MonthAddCount",monthAddCount);//本月新增设备
        map.put("YearCount",yearAddCount);//今年新增设备
        map.put("CollectDeviceCount",deviceCount);//设备总数

        return new BaseResponse("0", "成功",map);
    }
}
